package cn.itsource.pethome.system.user.service.impl;

import cn.itsource.pethome.constants.BaseConstants;
import cn.itsource.pethome.system.login.domain.PhoneRegister;
import cn.itsource.pethome.system.logininfo.domain.Logininfo;
import cn.itsource.pethome.system.logininfo.mapper.LogininfoMapper;
import cn.itsource.pethome.system.user.domain.User;
import cn.itsource.pethome.system.user.mapper.UserMapper;
import cn.itsource.pethome.system.user.service.IUserService;
import cn.itsource.pethome.base.service.impl.BaseServiceImpl;
import cn.itsource.pethome.utils.MD5Utils;
import cn.itsource.pethome.utils.StrUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zcj
 * @since 2023-01-11
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private LogininfoMapper logininfoMapper;

    @Override
    public User findByPhone(String phone) {
        return userMapper.findByPhone(phone);
    }

    @Override
    public Long add(PhoneRegister register) {
        //注册这里补充用户数据
        User user = new User();
        //先生成盐值
        String salt = StrUtils.getComplexRandomString(32);
        user.setSalt(salt);
        String saltPassword = MD5Utils.encrypByMd5(register.getPassword() + salt);
        user.setPassword(saltPassword);
        user.setCreatetime(new Date());
        user.setPhone(register.getPhone());
        user.setUsername(register.getPhone());
        user.setState(BaseConstants.User.STATE_NORMAL);
        userMapper.add(user);

        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(BaseConstants.Logininfo.STATE_USER);
        logininfo.setDisable(BaseConstants.Logininfo.DISABLE_1);
        logininfoMapper.add(logininfo);

        user.setLogininfoId(logininfo.getId());
        userMapper.update(user);
        return user.getId();
    }
}
